package com.nowoe.server.util;

import com.nowoe.server.constant.Http;
import com.nowoe.server.constant.StaticResource;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author 倚栏听风 2024/1/5 15:28
 */
public class StaticResourceUtil {
    /**
     * 获取绝对路径
     *
     * @param relativePath 相对路径
     * @return 绝对路径
     */
    public static String getAbsolutePath(String relativePath) {
        String absolutePath = StaticResourceUtil.class.getResource(StaticResource.template).getPath();
        return absolutePath.replaceAll("\\\\", "/") + relativePath;
    }

    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        int resourceSize = count;
        outputStream.write(HttpProtocolUtil.getHttpHeader(Http.SUCCESS, resourceSize).getBytes());
        long written = 0; // 已读的字节数
        int byteSize = 1024; // 一次读取的字节数
        byte[] bytes = new byte[byteSize];
        while (written < resourceSize) {
            if (written + byteSize > resourceSize) {
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written += byteSize;
        }
    }

}
